var app = getApp();
var utils = require("../../util/utils.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: [],
    totalCount: 0,
    totalMovies: [],
    isEmpty: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var categoryName = options.categoryName;
    this.setData({
      categoryName: categoryName
    })
    var publicUrl = app.globalUrl.doubanUrl;


    var allUrl = '';
    switch (options.categoryName) {
      case '正在热映':
        allUrl = publicUrl + `/v2/movie/in_theaters`;
        break;
      case '即将上映':
        allUrl = publicUrl + `/v2/movie/coming_soon`;
        break;
      case '排行榜':
        allUrl = publicUrl + `/v2/movie/top250`;
        break;
    };
    this.setData({
      allUrl: allUrl
    })
    //进行网络请求数据
    utils.http(allUrl, this.callback);
    wx.showNavigationBarLoading();
  },
  onReachBottom: function(e) {
    var nextUrl = this.data.allUrl + '?start=' + this.data.totalCount + '&count=20';
    utils.http(nextUrl, this.callback);
    wx.showNavigationBarLoading();
  },
  callback: function(res) {
    var movies = [];
    for (var idx in res.subjects) {
      var subject = res.subjects[idx];
      var title = subject.title;
      //名字过长处理一下
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      };
      var temp = {
        coverageUrl: subject.images.large,
        title: title,
        star: utils.covertToStarsArray(subject.rating.stars),
        average: subject.rating.average,
        movieid: subject.id
      }
      movies.push(temp)
    }
    var totalMovies = [];
    /**
     * concat合并数组
     * 判断是不是第一次进入，如果是不需要累加
     * 
     */
    if (!this.data.isEmpty) {
      //非第一次进入  以前更新到data中的movies加上刚刚获取的movies
      totalMovies = this.data.movies.concat(movies)
    } else {
      totalMovies = movies;
      this.data.isEmpty = false;
    }
    this.setData({
      movies: totalMovies
    })
    this.data.totalCount += 20;
    wx.hideNavigationBarLoading();
  },



  onReady: function() {
    wx.setNavigationBarTitle({
      title: this.data.categoryName
    })

  }
  //页面滚到到底部上拉加载


})